package com.example.wotu;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.app.Activity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.Calendar;

public class LogoinScreen extends AppCompatActivity {

    private SQLiteDatabase sql;
    private TextView rxzz;
    private Button rxdl;
    private EditText logn;
    private EditText logp;
    private Switch logswitch;
    private long exiT;
    private int SSI = 0;

    //动态读写权限
    private static String[] AndroidPermission = {"android.permission.READ_EXTERNAL_STORAGE", "WRITE_EXTERNAL_STORAGE"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.logoin_screen);

        getFindV();
        versPremission(LogoinScreen.this);
        SETOnClick();
    }

    private void getFindV(){
        rxzz = findViewById(R.id.RXzz);
        rxdl = findViewById(R.id.RXdl);
        logn = findViewById(R.id.LOGname);
        logp = findViewById(R.id.LOGpasw);
        logswitch = (Switch)findViewById(R.id.logswitch);
        logswitch.setChecked(false);
        logn.setText("");
        logp.setText("");
    }
    //2.动态获取手机权限
    public static void versPremission(Activity activity) {
        //判断是否有权限，否则添加
        if (ActivityCompat.checkSelfPermission(activity, "android.permission.WRITE_EXTERNAL_STORAGE")
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, AndroidPermission, 1);
        }
    }
    //3.注册；4.登录
    private void SETOnClick(){
        rxzz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(logn.getText().toString().length() > 0 && logp.getText().toString().length() > 0){
                    if(logn.getText().toString().length() > 2 && logp.getText().toString().length() > 6){
                        new AlertDialog.Builder(LogoinScreen.this)
                            .setIcon(R.mipmap.ic_launcher)
                            .setTitle("红墨提示：")
                            .setMessage("是否使用注册此账号？")
                            .setNeutralButton("确认", new DialogInterface.OnClickListener() {     //左边
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    SqlSelORInt(0);
                                }
                            })
                            .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {

                                }
                            }).create().show();
                    }else Toast.makeText(LogoinScreen.this,"1.账号需超过2字以上！\n2.密钥超过6字以上！\n3.而两则不超过10字！",Toast.LENGTH_SHORT).show();
                }else Toast.makeText(LogoinScreen.this,"请输入需要进行入选的双向信息！",Toast.LENGTH_LONG).show();
            }
        });
        rxdl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(logn.getText().toString().length() > 0 && logp.getText().toString().length() > 0){
                    if(SqlSelORInt(1) == 1){
                        if(SSI > 0){
                            Intent in = new Intent(LogoinScreen.this,MainActivity.class);
                            Bundle bu = new Bundle();
                            bu.putInt("useid",SSI);
                            in.putExtras(bu);
                            startActivity(in);
                        }
                    }
                }else Toast.makeText(LogoinScreen.this,"请输入需要进行入选的双向信息！",Toast.LENGTH_SHORT).show();
            }
        });
    }
    private int SqlSelORInt(int L){
        Calendar c1 = Calendar.getInstance();
        sql = new MySQLOpen(LogoinScreen.this).getReadableDatabase();
        try{
            Cursor cs = sql.rawQuery("select * from use where account = ? and password = ?",
                    new String[]{logn.getText().toString().trim(),logp.getText().toString()});
            if(L == 1){     //登录
                if(cs.moveToFirst()){
                    do{
                        //利用sql漏洞注入操作一些特别操作
                        if(logswitch.isChecked()){
                            sql.rawQuery("update use set usetruef = 0 where 1 = 1",null);
                            ContentValues val = new ContentValues();
                            val.put("finaltime",c1.get(Calendar.YEAR)+"-"+(c1.get(Calendar.MONTH)+1)+"-"+c1.get(Calendar.DATE));
                            val.put("usetruef",1);
                            sql.update("use",val,"useid = ?",new String[]{String.valueOf(cs.getInt(0))});
                        }
                        SSI = cs.getInt(0);
                        sql.close();
                        return 1;
                    }while (cs.moveToNext());
                }else Toast.makeText(LogoinScreen.this,"登录失败！",Toast.LENGTH_SHORT).show();
            }
            else if(L == 0){    //注册
                if(cs.moveToFirst()) Toast.makeText(LogoinScreen.this,"已存在！",Toast.LENGTH_SHORT).show();
                else{
                    String date = c1.get(Calendar.YEAR)+"-"+(c1.get(Calendar.MONTH)+1)+"-"+c1.get(Calendar.DATE)+" "+c1.get(Calendar.HOUR_OF_DAY)+":"+c1.get(Calendar.MINUTE)+":"+c1.get(Calendar.SECOND);
                    ContentValues val = new ContentValues();
                    val.put("account",logn.getText().toString().trim());
                    val.put("password",logp.getText().toString().trim());
                    val.put("Createtime",date);
                    val.put("usetruef",0);
                    sql.insert("use",null,val);
                    Toast.makeText(LogoinScreen.this,"注册成功！",Toast.LENGTH_SHORT).show();
                    sql.close();
                    return 1;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            sql.close();
            Toast.makeText(LogoinScreen.this,"登录错误！",Toast.LENGTH_SHORT).show();
        }
        return 0;
    }

    @Override
    public void onBackPressed() {
        if((System.currentTimeMillis()-exiT)>2000){
            Toast.makeText(LogoinScreen.this,"是否退出红墨？",Toast.LENGTH_SHORT).show();
            exiT=System.currentTimeMillis();
        }else{
            Toast.makeText(LogoinScreen.this,"已退出",Toast.LENGTH_SHORT).show();
            finishAffinity();
        }
    }
}
